<?php

namespace login\model;

require_once("UserName.php");
require_once("Password.php");
require_once("UserCredentials.php");
require_once("TemporaryPasswordServer.php");


class LoginDAL {

	/**
	 * @var \mysqli
	 */
	private $mysqli;

	/**
	 * @param \mysqli $mysqli
	 */
	function __construct(\mysqli $mysqli) {
		$this->mysqli = $mysqli;
	}


	/**
	 * @param  string  $username      
	 * @param  boolean $searchForUser
	 * @return \login\model\UserCredentials
	 */
	public function getUser($username) {
		$sqlQ = "SELECT `UserName`, `PW` FROM `Users` WHERE `UserName` = ?";

		$stmt = $this->mysqli->prepare($sqlQ);
		if ($stmt == false) {
			throw new \Exception("Prepare of sql question failed" . $this->mysqli->error);
		}
		$res = $stmt->bind_param("s", $username);
		if ($res == false) {
			throw new \Exception("Bind param failed " . $stmt->error);
		}
		$res = $stmt->execute();
		if($res == false) {
			throw new \Exception("Database execute failed " . $stmt->error);
		}
		$res = $stmt->bind_result($username, $password);
		if ($res == false) {
			throw new \Exception("Bind result failed " . $stmt->error);
		}

		if($stmt->fetch()) {
			$uName = $username;
			$pWord = $password;
			
			$UsrName = new \login\model\UserName($uName);

			return new \login\model\UserCredentials($UsrName,
													\login\model\Password::fromCleartext($pWord),
													new \login\model\TemporaryPasswordServer());
		}
		throw new \Exception("Find no user");
	}
}